const api = {};

api.tMailTimePlus = "0";
api.tMailNetWorkDelay = "0";

api.jdTimePlus = "0";
api.jdNetWorkDelay = "0";

threads.start(function () {
  getTMailPlus();
});

threads.start(function () {
  getJDPlus();
});

// 计算天猫时间
function getTMailPlus() {
  let successTime = 0;
  let sumTime = 0;
  let apiStart = new Date().getTime();
  // 循环5次取均值
  for (let i = 0; i < 5; i++) {
    const res = getTMailTime();
    if (res && res.state === "success") {
      successTime += 1;
      sumTime += res.time;
    }
  }
  api.tMailNetWorkDelay = String(
    ((new Date().getTime() - apiStart) / 10).toFixed(0)
  );

  api.tMailTimePlus =
    String((sumTime / successTime).toFixed(0)) !== "0"
      ? String((sumTime / successTime).toFixed(0))
      : "1";
}

/**
 * 获取天猫时间，差值正数则比设备快，负数则比设备慢
 */
function getTMailTime() {
  const res = http.get(
    "http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp"
  );
  if (res.statusCode != 200) {
    toast("请求失败: " + res.statusCode + " " + res.statusMessage);
  } else {
    const tMailTime = JSON.parse(res.body.string()).data.t;
    const deviceTime = new Date().getTime();
    const tempTime = tMailTime - deviceTime;

    return {
      state: "success",
      time: tempTime,
    };

    // 差值大于2000则不进行计算
    // if (tempTime > -2000 && tempTime < 2000) {
    //   return {
    //     state: "success",
    //     time: tempTime,
    //   };
    // } else {
    //   return {
    //     state: "error",
    //   };
    // }
  }
}

// 计算京东时间
function getJDPlus() {
  let successTime = 0;
  let sumTime = 0;
  let apiStart = new Date().getTime();
  // 循环5次取均值
  for (let i = 0; i < 5; i++) {
    const res = getJDTime();
    if (res && res.state === "success") {
      successTime += 1;
      sumTime += res.time;
    }
  }
  api.jdNetWorkDelay = String(
    ((new Date().getTime() - apiStart) / 10).toFixed(0)
  );

  api.jdTimePlus =
    String((sumTime / successTime).toFixed(0)) !== "0"
      ? String((sumTime / successTime).toFixed(0))
      : "1";
}

/**
 * 获取京东时间，差值正数则比设备快，负数则比设备慢
 */
function getJDTime() {
  return {
    state: "error",
  };
  const res = http.get("http://a.jd.com//ajax/queryServerData.html");
  if (res.statusCode != 200) {
    toast("请求失败: " + res.statusCode + " " + res.statusMessage);
  } else {
    const JDTime = JSON.parse(res.body.string()).serverTime;
    const deviceTime = new Date().getTime();
    const tempTime = JDTime - deviceTime;

    return {
      state: "success",
      time: tempTime,
    };

    // 差值大于2000则不进行计算
    // if (tempTime > -2000 && tempTime < 2000) {
    //   return {
    //     state: "success",
    //     time: tempTime,
    //   };
    // } else {
    //   return {
    //     state: "error",
    //   };
    // }
  }
}

module.exports = api;
